<?php
/**
 * Created by Benjiemin
 * Date: 2020/2/28
 * Time: 10:43
 */
require ('./vendor/autoload.php');
use QL\QueryList;
use QL\Ext\Chrome;
require ('./aip-php-sdk-2.2.15/AipOcr.php');

class Win3008
{
    const BaseUrl = 'http://nc1.win3008.com/';
    private $username = 'nn301';
    private $password = 'qwe123123';
    private $cookiesFile = 'win3008_cokies.json';
    private $desc_url = 'http://106.52.105.157:81/';

    /**
     * 执行登录，替换原有的cookies
     */
    public function updateCookies()
    {
        $ql = QueryList::getInstance();
        // 注册插件，默认注册的方法名为: chrome
        $ql->use(Chrome::class);
        $ql->chrome(function ($page, $browser) {
            $username = $this->username;
            $password = $this->password;
            $page->goto(self::BaseUrl . 'member/login');
            $filename = 'verify.jpeg';
            //获取页面截图
            $page->screenshot([
                'path' => $filename,
                'fullPage' => true
            ]);

            //验证码识别
            $appId = '9360309';
            $apiKey = 'f94FyaKX2LKx0GWBoddFVpxa';
            $secretKey = 'oGhM9QqHH6qslErF1LH8etP6Ber5adDz';
            $apiOcrModel = new AipOcr($appId, $apiKey, $secretKey);
            $verifyRet = $apiOcrModel->basicGeneral(file_get_contents($filename));

            if (!isset($verifyRet['words_result'][5]['words'])) {
                echo '识别验证码失败';
                die;
            }
            $validateCode = $verifyRet['words_result'][5]['words'];

            // 这里故意设置一个很长的延长时间，让你可以看到chrome浏览器的启动
            $page->type("input[name='loginName']", $username);
            $page->type("input[name='loginPwd']", $password);
            $page->type("input[name='ValidateCode']", $validateCode);

            $page->click("input[name='Submit']");
            //登录
            $html = $page->content();
            sleep(1);
            //点击确认登录
            $page->click("#Submit");
            //点击新闻
            $page->goto(self::BaseUrl . 'news/text/0?0.21222746993288832');
            //获取cookies
            $cookies = $page->cookies(self::BaseUrl . 'member/');
            file_put_contents($this->cookiesFile, json_encode($cookies));
        }, [
            'headless' => false, // 启动可视化Chrome浏览器,方便调试
            'devtools' => false, // 打开浏览器的开发者工具
        ])->find('title')->text();
        return true;
    }

    /**
     * 获取cookies
     */
    public function getCookies()
    {
        $file = $this->cookiesFile;
        if (!is_file($file)) {
            $this->updateCookies();
        }
        $cookiesJson = file_get_contents($file);
        $cookiesArr = json_decode($cookiesJson, true);
        $returnData = array();
        foreach ($cookiesArr as $cookie) {
            $returnData[$cookie['name']] = $cookie['value'];
        }
        return $returnData;
    }


    /**把彩票代码转换为win3008彩票代码
     * @param $code
     * @return bool|mixed
     */
    private function switchLotteryCode($code)
    {
        $codeArr = array(
            '10005' => 2,//广东快乐10分
            '50021' => 3,//重庆欢乐生肖
            '10001' => 4,//北京赛车PK10
            '4' => 7,//Pc蛋蛋
            '10136' => 8,//幸运飞艇
            '10004' => 9,//新疆时时彩
            '7' => 10,//澳洲欢乐5
            '8' => 11,//澳洲欢乐10
            '9' => 12,//极速时时彩
            '10' => 13,//极速赛车
        );
        if (isset($codeArr[$code])) {
            return $codeArr[$code];
        }
        return false;
    }

    /**
     * @param $gameTypeLann
     * @param $location位置
     * @param $betBall投注球
     */
    private function switchCode($gameTypeLann, $location, $betBall)
    {
        switch ($gameTypeLann) {
            case '8'://幸运飞艇
                if (strlen($location) > 1) {
                    $location = substr($location, 1, 1);
                }
                return $gameTypeLann . str_pad(($betBall - 1), 2, 0, STR_PAD_LEFT) . $location;
                break;
            default:
                return 0;
        }
    }

    /**获取请求的头文件
     * @return array
     */
    private function getHeader()
    {
        $cookiesArr = $this->getCookies();
        $headers = [
            'Host' => 'nc1.win3008.com',
            'Pragma' => 'no-cache',
            'Cache-Control' => 'no-cache',
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
            'Referer' => self::BaseUrl,
            'Accept' => '*/*',
            'Accept-Encoding' => 'gzip, deflate',
            'Upgrade-Insecure-Requests' => '1',
            'Origin' => 'http://nc1.win3008.com',
            'Cookie' => "dispcl=0;PHPSESSID={$cookiesArr['PHPSESSID']}; SERVER_ID={$cookiesArr['SERVER_ID']}; betquick=0; GameTypeLann=4",
            'Connection' => 'keep-alive'
        ];
        return $headers;
    }

    /**
     * get请求
     */
    private function getRequest($url, $times = 0)
    {
        if ($times > 2) {
            return false;
        }

        $res = QueryList::get($url, [
        ],
            [
                'timeout' => 30,
                'headers' => $this->getHeader(),
            ]
        );
        $html = $res->getHtml();
        //没获取到信息，更新cookies
        if (empty($html)) {
            $this->updateCookies();
            $this->getRequest($url, $times + 1);
        }
        return $html;
    }

    /**XML转数组
     * @param $xml
     * @return mixed
     */
    private function xmlToArray($xml)
    {
        echo $xml . PHP_EOL;
        $xml = simplexml_load_string(trim($xml), 'SimpleXMLElement');
        return json_decode(json_encode($xml), TRUE);
    }

    /**
     * 获取赔率请求地址
     */
    public function getRateUrl($code, $times = 0)
    {
        if ($times > 2) {
            return false;
        }
        $selfCode = $this->switchLotteryCode($code);
        if (!$selfCode) {
            return false;
        }

        switch ($selfCode) {
            case '8'://幸运飞艇
                $url = self::BaseUrl . "member/pt8/betdrawxmldata/?pcid2=801,802,803,804,805,806,807,808,809,810&0.".time();
                break;
            case '3'://重庆欢乐生肖
                $url = self::BaseUrl . "member/pt3/betdrawxmldata/?pcid2=301,302,303,304,305,306,307,308,309,310,311,312,313&0.3551725915163002";
                break;
            case '2'://广东快乐10分
                $url = self::BaseUrl . "member/pt2/betdrawxmldata/?pcid2=209,210,211,212,215,216,217,218&0.5876573288814646";
                break;
            case '4'://北京赛车PK10
                $url = self::BaseUrl . "member/pt4/betdrawxmldata/?pcid2=411,412,413,414,415&0.21742188705714427";
                break;
            case '7'://PC蛋蛋
                $url = self::BaseUrl . "member/pt7/betdrawxmldata/?pcid2=702,703,704,705,706,707,711,712,713,714&0.08398506963838814";
                break;
            case '9'://新疆时时彩
                $url = self::BaseUrl . "member/pt9/betdrawxmldata/?pcid2=901,902,903,904,905,906,907,908,909,910,911,912,913&0.4341335102617949";
                break;
            case '10'://澳洲欢乐5
                $url = self::BaseUrl . "member/pt10/betdrawxmldata/?pcid2=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013&" . time();
                break;
            default:
                $url = self::BaseUrl . 'member/pt9/betdrawxmldata/';
        }
        return $url;
    }


    /**写日志
     * @param $filename
     * @param $msg
     */
    public static function log($msg, $filename = 'daily')
    {
        $folder = 'log';
        if (!file_exists($folder)) {
            mkdir($folder, 7777);
        }

        $filename = $folder . '/' . date("Ymd") . $filename . '.txt';
        if (is_array($msg)) {
            $msg = json_encode($msg, JSON_UNESCAPED_UNICODE);
        }
        $msg = date("Y-m-d H:i:s") . ':' . $msg . PHP_EOL . PHP_EOL;
        if (!file_exists($filename)) {
            touch($filename);
        }
        file_put_contents($filename, $msg, FILE_APPEND);
    }

        public function xmlObjToArr($obj)
        {
            $namespace = $obj->getDocNamespaces(true);
            $namespace[NULL] = NULL;

            $children = array();
            $attributes = array();
            $name = strtolower((string)$obj->getName());

            $text = trim((string)$obj);
            if (strlen($text) <= 0) {
                $text = NULL;
            }

            if (is_object($obj)) {
                foreach ($namespace as $ns => $nsUrl) {
                    $objAttributes = $obj->attributes($ns, true);
                    foreach ($objAttributes as $attributeName => $attributeValue) {
                        $attribName = strtolower(trim((string)$attributeName));
                        $attribVal = trim((string)$attributeValue);
                        if (!empty($ns)) {
                            $attribName = $ns . ':' . $attribName;
                        }
                        $attributes[$attribName] = $attribVal;
                    }
                    $objChildren = $obj->children($ns, true);
                    foreach ($objChildren as $childName => $child) {
                        $childName = strtolower((string)$childName);
                        if (!empty($ns)) {
                            $childName = $ns . ':' . $childName;
                        }
                        $children[$childName][] = xmlObjToArr($child);
                    }
                }
            }

            return array(
                'name' => $name,
                'text' => $text,
                'attributes' => $attributes,
                'children' => $children
            );
        }

    /**
     * 登录并拉去订单投注
     */
    public function login(){
        $ql = QueryList::getInstance();
        // 注册插件，默认注册的方法名为: chrome
        $ql->use(Chrome::class);
        $ql->chrome(function ($page,$browser) {
            $username = $this->username;
            $password = $this->password;
            $page->goto(self::BaseUrl.'member/login');
            $filename = 'verify.jpeg';
            //获取页面截图
            $page->screenshot([
                'path' => $filename,
                'fullPage' => true
            ]);

            //验证码识别
            $appId = '9360309';
            $apiKey = 'f94FyaKX2LKx0GWBoddFVpxa';
            $secretKey = 'oGhM9QqHH6qslErF1LH8etP6Ber5adDz';
            $apiOcrModel = new AipOcr($appId, $apiKey, $secretKey);
            $verifyRet = $apiOcrModel->basicGeneral( file_get_contents($filename ));

            if(!isset($verifyRet['words_result'][5]['words'])){
                echo '识别验证码失败';die;
            }
            $validateCode =  $verifyRet['words_result'][5]['words'];

            // 这里故意设置一个很长的延长时间，让你可以看到chrome浏览器的启动
            $page->type("input[name='loginName']",$username);
            $page->type("input[name='loginPwd']",$password);
            $page->type("input[name='ValidateCode']",$validateCode);
            $page->click("input[name='Submit']");
            //登录
            sleep(1);
            //点击确认登录
            $page->click("#Submit");
            sleep(1);
            //点击新闻
            $page->goto(self::BaseUrl.'news/text/0?0.'.time());
            //获取cookies
            $cookies = $page->cookies(self::BaseUrl.'member/');
            if(empty($cookies)){
               $this->log('cookies获取失败');die;
            }
            $cookiesArr = array();
            foreach ($cookies as $cookie){
               $cookiesArr[$cookie['name']] = $cookie['value'];
            }
            $time = time();
            $i = 1;
            while((time()-$time)<60){
                //拉取订单
                $url = 'http://106.52.105.157:81/';
                $orderJson = QueryList::get($url.'order/get-member-order')->getHtml();
                echo "第{$i}次拉取订单".PHP_EOL;
                if(empty( $orderJson)){
                    echo '订单获取失败'.PHP_EOL;
                    $this->log('订单获取失败');
                    sleep(1);
                    continue;
                }

                $dataArr = json_decode($orderJson,true);
                $orderDataArr = $dataArr['data'];
                if(empty($orderDataArr)){
                    echo '没有订单数据'.PHP_EOL;
                    sleep(1);
                    continue;
                }
                echo '收到订单，开始遍历订单'.PHP_EOL;
                foreach ($orderDataArr as $order){
                    $betBallsArr = explode(',' ,$order['bet_balls']);
                    sleep(5);
                    //获取赔率
                    $rateUrl = $this->getRateUrl($order['gameid']);
                    $page->goto($rateUrl);
                    $html = $page->content();

                    file_put_contents('peilv.html',$html);
                    $ql = QueryList::html($html);
                    // 获取投注期号
                    $drawid = $ql->find('root periodid')->text();
                    if(empty($drawid)){
                        $this->log('drawid获取失败或者未开盘'.json_encode($order));
                        echo 'drawid获取失败或者未开盘'.PHP_EOL;
                        $this->callBack($order['orderno'],0);
                        sleep(1);continue;
                    }
                    //余额,这边需求投注之前判断余额
                    $balance = $ql->find('root balance')->text();
                    if(empty($balance)){
                        echo 'balance获取失败'.PHP_EOL;
                        $this->log('balance获取失败'.json_encode($order));
                        $this->callBack($order['orderno'],0);
                        sleep(1);continue;
                    }

                    $gameTypeLann = $this->switchLotteryCode($order['gameid']);
                    $pidStr = '';
                    $oddStr = '';
                    $betMoneyStr = '';
                    var_dump($order);
                    //生成订单数据
                    foreach ($betBallsArr as $betBall){
                        $betMoneyStr = $betMoneyStr.','.$order['bet_money'];
                        $p_id = $this->switchCode($gameTypeLann,$order['bet_number'],$betBall);
                        $p_id_odd = $ql->find("bet[id={$p_id}]")->text();
                        if(!empty($p_id)){
                            $pidStr = $pidStr.','.$p_id;
                        }
                        if(empty($p_id_odd)){
                            sleep(3);
                            $ql = QueryList::html($html);
                            $p_id_odd = $ql->find("bet[id={$p_id}]")->text();
                        }
                        $oddStr = $oddStr.','.$p_id_odd;
                    }
                    $pidStr = trim($pidStr,',');
                    $oddStr = trim($oddStr,',');
                    $betMoneyStr = trim($betMoneyStr,',');
                    $betUrl = self::BaseUrl.'member/bet/'.$gameTypeLann;
                    if(strtotime($order['stop_time'])<time()){
                        echo '已经封盘'.PHP_EOL;
                        $this->log('已经封盘'.json_encode($order));
                        //判断下单是否成功，并回调
                        $this->callBack($order['orderno'],0);
                       continue;
                    }
                    //投注
                    $betRet= QueryList::post($betUrl, [
                        'draw_ID' => ($drawid),
                        'p_ID'=>$pidStr,
                        'p_Odds' => $oddStr,
                        'bet_Money' =>$betMoneyStr,
                        'checksum' => mt_rand(10000,99999),
                        'ms_1' => '50',
                        'ms_2' => '100',
                        'ms_3' => '200',
                        'ms_4' => '500',
                        'ms_5' => '1000',
                        'ms_6' => '5000',
                    ],
                        [
                            'timeout' => 30,
                            'headers' => [
                                'Referer' => 'http://nc1.win3008.com/lottery/pt8/css/ball.css',
                                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
                                'Accept'     => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                                'Accept-Encoding'      => 'gzip, deflate',
                                'Upgrade-Insecure-Requests'=>'1',
                                'Origin'=>self::BaseUrl,
                                'Host'=>'nc1.win3008.com',
                                'Cookie'    =>"PHPSESSID={$cookiesArr['PHPSESSID']}; SERVER_ID={$cookiesArr['SERVER_ID']}; betquick=0; GameTypeLann=".$gameTypeLann
                            ]
                        ]
                    );
                    echo "第{$i}次投注订单".PHP_EOL;
                    //投注结束，判断投注结果
                    file_put_contents($order['orderno'].'ret.html',$betRet);
                    $ret = 1;
                    if(strpos($html,'盘口未开盘')!==false){
                        $ret = 0;
                    }
                    //判断下单是否成功，并回调
                    $this->callBack($order['orderno'],$ret);
                    $i = $i+1;
                }
            }
             $browser->close();
            //投注
        },[
            'idle_timeout' => 1000000 ,
            'timeout' => 0,
            'headless' => false, // 启动可视化Chrome浏览器,方便调试
            'devtools' => false, // 打开浏览器的开发者工具
        ])->find('title')->text();
        return true;
    }

    /**下单回调
     * @param $orderno
     * @param $ret
     */
    private function callBack($orderno,$ret){
        $callBackUrl = $this->desc_url.'order/bet-status-callback';
        echo "回传下单结果，订单号{$orderno}，结果：{$ret}".PHP_EOL;
        QueryList::post($callBackUrl, [
            'orderno' => $orderno,
            'ret' => $ret,//成功1，不成功0
        ],
            [
                'timeout' => 30,
                'headers' => [
                    'Referer' => 'http://nc1.win3008.com/lottery/pt8/css/ball.css',
                    'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
                    'Accept'     => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                    'Accept-Encoding'      => 'gzip, deflate',
                    'Upgrade-Insecure-Requests'=>'1',
                    'Origin'=>self::BaseUrl,
                    'Host'=>'nc1.win3008.com',
                ]
            ]
        );
    }






}